import { useState, useEffect, useRef } from 'react';
import { cn } from '@/lib/utils';

// 定义搜索引擎接口
interface SearchEngine {
  id: string;
  name: string;
  url: string;
  icon: string;
}

export default function SearchBar() {
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedEngine, setSelectedEngine] = useState<SearchEngine | null>(null);
  const [showEngines, setShowEngines] = useState(false);
  const engineRef = useRef<HTMLDivElement>(null);
  
  // 搜索引擎配置，包含SVG图标
  const searchEngines: SearchEngine[] = [
    {
      id: 'google',
      name: 'Google',
      url: 'https://google.com/search?q=',
      icon: '<svg t="1757056003995" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" width="20" height="20"><path d="M214.101333 512c0-32.512 5.546667-63.701333 15.36-92.928L57.173333 290.218667A491.861333 491.861333 0 0 0 4.693333 512c0 79.701333 18.858667 154.88 52.394667 221.610667l172.202667-129.066667A290.56 290.56 0 0 1 214.101333 512" fill="#FBBC05"></path><path d="M516.693333 216.192c72.106667 0 137.258667 25.002667 188.458667 65.962667L854.101333 136.533333C763.349333 59.178667 646.997333 11.392 516.693333 11.392c-202.325333 0-376.234667 113.28-459.52 278.826667l172.373334 128.853333c39.68-118.016 152.832-202.88 287.146666-202.88" fill="#EA4335"></path><path d="M516.693333 807.808c-134.357333 0-247.509333-84.864-287.232-202.88l-172.288 128.853333c83.242667 165.546667 257.152 278.826667 459.52 278.826667 124.842667 0 244.053333-43.392 333.568-124.757333l-163.584-123.818667c-46.122667 28.458667-104.234667 43.776-170.026666 43.776" fill="#34A853"></path><path d="M1005.397333 512c0-29.568-4.693333-61.44-11.648-91.008H516.650667V614.4h274.602666c-13.696 65.962667-51.072 116.650667-104.533333 149.632l163.541333 123.818667c93.994667-85.418667 155.136-212.650667 155.136-375.850667" fill="#4285F4"></path></svg>'
    },
    {
      id: 'baidu',
      name: '百度',
      url: 'https://www.baidu.com/s?wd=',
      icon: '<svg t="1757058178057" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" width="20" height="20"><path d="M184.682 538.759c111.177-23.874 96.03-156.737 92.702-185.776-5.445-44.768-58.102-123.02-129.606-116.831-89.98 8.074-103.126 138.052-103.126 138.052-12.17 60.08 29.132 188.452 140.03 164.555zM302.746 769.86c-3.257 9.331-10.517 33.228-4.234 54.03 12.402 46.677 52.912 48.77 52.912 48.77h58.218v-142.31h-62.336c-28.016 8.354-41.535 30.157-44.56 39.51z m88.281-453.898c61.406 0 111.037-70.667 111.037-158.04C502.064 70.643 452.433 0 391.027 0c-61.312 0-111.06 70.643-111.06 157.923 0 87.373 49.77 158.04 111.06 158.04z m264.47 10.447c82.068 10.657 134.84-76.925 145.335-143.31 10.703-66.292-42.256-143.288-100.357-156.527-58.218-13.356-130.909 79.904-137.54 140.704-7.912 74.32 10.633 148.593 92.562 159.133z m201.086 390.213s-126.976-98.24-201.11-204.414C555 355.66 412.272 419.37 364.525 498.993 316.987 578.594 242.9 628.947 232.382 642.28c-10.68 13.124-153.385 90.166-121.694 230.87 31.669 140.612 142.939 137.936 142.939 137.936s81.998 8.074 177.12-13.217c95.168-21.104 177.096 5.26 177.096 5.26s222.284 74.435 283.108-68.852c60.754-143.334-34.368-217.654-34.368-217.654zM476.26 929.88H331.739c-62.406-12.449-87.257-55.03-90.398-62.29-3.072-7.376-20.802-41.604-11.425-99.845 26.968-87.257 103.87-93.516 103.87-93.516h76.926v-94.563l65.524 1V929.88z m269.146-1h-166.3c-64.453-16.614-67.455-62.407-67.455-62.407v-183.89l67.455-1.094v165.276c4.119 17.637 26.015 20.825 26.015 20.825h68.525V682.581h71.76v246.297z m235.408-490.99c0-31.76-26.387-127.394-124.23-127.394-98.008 0-111.108 90.258-111.108 154.06 0 60.894 5.142 145.894 126.883 143.195 121.788-2.7 108.455-137.936 108.455-169.86z m0 0" fill="#3245DF"></path></svg>'
    },
    {
      id: 'bing',
      name: 'Bing',
      url: 'https://www.bing.com/search?q=',
      icon: '<svg t="1757059391817" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" width="20" height="20"><path d="M119.466667 887.466667h-6.826667c-6.826667-3.413333-10.24-10.24-10.24-17.066667V17.066667c0-6.826667 3.413333-10.24 6.826667-13.653334 3.413333-3.413333 10.24-3.413333 17.066666-3.413333l238.933334 85.333333c6.826667 3.413333 10.24 10.24 10.24 17.066667v563.2c0 3.413333-3.413333 10.24-6.826667 13.653333l-238.933333 204.8c-3.413333 3.413333-6.826667 3.413333-10.24 3.413334zM136.533333 40.96v791.893333l204.8-174.08V116.053333L136.533333 40.96z" fill="#1296db"></path><path d="M358.4 1024c-3.413333 0-6.826667 0-6.826667-3.413333l-238.933333-136.533334c-6.826667-3.413333-10.24-6.826667-10.24-13.653333s3.413333-10.24 10.24-13.653333l785.066667-426.666667c6.826667-3.413333 10.24-3.413333 17.066666 0s6.826667 10.24 6.826667 13.653333v221.866667c0 6.826667-3.413333 10.24-6.826667 13.653333l-546.133333 341.333334c-3.413333 3.413333-6.826667 3.413333-10.24 3.413333z m-204.8-153.6l204.8 116.053333L887.466667 655.36v-184.32L153.6 870.4z"></path><path d="M716.8 563.2h-3.413333L525.653333 512c-3.413333 0-10.24-3.413333-10.24-10.24l-102.4-238.933333c-3.413333-6.826667 0-13.653333 3.413334-17.066667 3.413333-6.826667 10.24-6.826667 17.066666-6.826667l477.866667 187.733334c6.826667 3.413333 10.24 6.826667 10.24 13.653333s-3.413333 13.653333-10.24 17.066667l-187.733333 102.4c0 3.413333-3.413333 3.413333-6.826667 3.413333z m-174.08-81.92l174.08 47.786667 150.186667-81.92-409.6-160.426667 85.333333 194.56z" fill="#1296db"></path></svg>'
    },
    {
      id: 'sogou',
      name: '搜狗',
      url: 'https://www.sogou.com/web?query=',
      icon: '<svg t="1757059490045" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" width="20" height="20"><path d="M1015.062344 508.169576c0-280.897756-227.27182-508.169576-508.169576-508.169576C228.548628 0 1.276808 227.27182 1.276808 508.169576s227.27182 508.169576 508.169576 508.169576c66.394015 0 130.234414-12.76808 191.521197-38.304239 76.608479-30.643392 145.55611-81.715711 199.182045-148.109726 71.501247-86.822943 114.912718-199.182045 114.912718-321.755611zM677.985037 939.730673c-56.179551 17.875312-109.805486 30.643392-168.538653 30.643392-255.361596 0-462.204489-206.842893-462.204489-462.204489S254.084788 45.965087 509.446384 45.965087 971.650873 252.80798 971.650873 508.169576c0 112.359102-40.857855 217.057357-109.805486 298.773067-48.518703 58.733167-112.359102 104.698254-183.86035 132.78803z" fill="#FA4D23"></path><path d="M499.23192 699.690773s-183.860349 2.553616-286.004987-91.930174L205.566085 737.995012s607.760599 219.610973 612.86783-132.788029c0 0 12.76808-84.269327-206.842893-143.002494 0 0-86.822943-20.428928-183.860349-76.608479 0 0-53.625935-61.286783 99.591023-48.518703 181.306733 15.321696 275.790524 61.286783 275.790523 61.286783V283.451372s-413.685786-155.770574-574.563591 22.982543c0 0-53.625935 81.715711 2.553616 132.78803s168.538653 114.912718 316.648379 153.216958c0-2.553616 191.521197 86.822943-48.518703 107.25187z" fill="#FA4D23"></path></svg>'
    }
  ];
  
  // 从localStorage加载保存的搜索引擎偏好
  useEffect(() => {
    const savedEngine = localStorage.getItem('preferredSearchEngine');
    if (savedEngine && searchEngines.some(engine => engine.id === savedEngine)) {
      setSelectedEngine(searchEngines.find(engine => engine.id === savedEngine) || searchEngines[0]);
    } else {
      setSelectedEngine(searchEngines[0]); // 默认使用Google
    }
  }, []);
  
  // 点击外部区域关闭搜索引擎选择面板
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (engineRef.current && !engineRef.current.contains(event.target as Node)) {
        setShowEngines(false);
      }
    };
    
    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);
  
  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    if (searchQuery.trim() && selectedEngine) {
      window.open(`${selectedEngine.url}${encodeURIComponent(searchQuery)}`, '_blank');
      setSearchQuery('');
    }
  };
  
  const handleEngineSelect = (engine: SearchEngine) => {
    setSelectedEngine(engine);
    localStorage.setItem('preferredSearchEngine', engine.id); // 保存到localStorage
    setShowEngines(false);
  };
  
  if (!selectedEngine) return null;
  
  return (
    <div className="w-full max-w-md mx-auto relative mt-8 mb-12" ref={engineRef}>
      <form onSubmit={handleSearch} className="relative">
        <div className="absolute left-3 top-1/2 transform -translate-y-1/2 z-10">
          <button
            type="button"
            onClick={() => setShowEngines(!showEngines)}
            className="flex items-center space-x-2 bg-white/80 dark:bg-gray-800/80 rounded-full px-2 py-1.5 shadow-sm hover:shadow-md transition-all duration-200"
            aria-label="选择搜索引擎"
          >
            <div 
              className="w-5 h-5 flex items-center justify-center"
              dangerouslySetInnerHTML={{ __html: selectedEngine.icon }}
            ></div>
            <i className={`fa-solid fa-chevron-down text-xs text-gray-500 transition-transform duration-200 ${showEngines ? 'rotate-180' : ''}`}></i>
          </button>
          
          {/* 搜索引擎选择面板 */}
          {showEngines && (
             <div className="absolute left-0 top-full mt-1 w-40 bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-200 dark:border-gray-700 overflow-hidden z-50 animate-in fade-in-50 zoom-in-95 duration-150">
              {searchEngines.map(engine => (
                <button
                  key={engine.id}
                  type="button"
                  onClick={() => handleEngineSelect(engine)}
                  className={`w-full flex items-center space-x-3 px-4 py-2 text-left hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors ${selectedEngine.id === engine.id ? 'bg-gray-100 dark:bg-gray-700' : ''}`}
                >
                  <div 
                    className="w-5 h-5 flex items-center justify-center flex-shrink-0"
                    dangerouslySetInnerHTML={{ __html: engine.icon }}
                  ></div>
                  <span className="text-sm text-gray-800 dark:text-gray-200">{engine.name}</span>
                  {selectedEngine.id === engine.id && (
                    <i className="fa-solid fa-check text-xs text-blue-500 ml-auto"></i>
                  )}
                </button>
              ))}
            </div>
          )}
        </div>
        
        <input
          type="text"
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
          placeholder={`在${selectedEngine.name}中搜索...`}
           className="w-full py-3 pl-20 pr-10 rounded-full bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500 text-gray-900 dark:text-gray-100 text-sm transition-all duration-200 shadow-sm"
          autoFocus
        />
        <button 
          type="submit"
          className="absolute right-4 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
          aria-label="搜索"
        >
          <i className="fa-solid fa-search"></i>
        </button>
      </form>
    </div>
  );
}